package com.ramnight.unify.boot.jdbc;

import java.beans.PropertyDescriptor;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import com.alibaba.fastjson.PropertyNamingStrategy;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ramnight.unify.kit.UnifyHolder;

// 内部使用，不对外
class SqlGen {
	private static Map<UnifyHolder, String> insertSqlCache = Maps.newConcurrentMap();

	static String getInsertSql(Class<?> entityClass, Set<String> excludeFieldSet) {
		UnifyHolder holder = UnifyHolder.of(entityClass, excludeFieldSet);
		return insertSqlCache.computeIfAbsent(holder, h -> doGetInsertString(entityClass, excludeFieldSet));
	}

	private static String doGetInsertString(Class<?> clazz, Set<String> excludeFieldSet) {
		PropertyDescriptor[] ds = BeanUtils.getPropertyDescriptors(clazz);
		List<String> fieldList = Lists.newArrayList();
		List<String> valueList = Lists.newArrayList();
		for (PropertyDescriptor p : ds) {
			String fn = p.getName();
			if (p.getPropertyType() == Class.class || excludeFieldSet.contains(fn)) {
				continue; // 跳过class字段
			}
			fieldList.add(PropertyNamingStrategy.SnakeCase.translate(fn));
			valueList.add(":" + fn);
		}

		String entityName = StringUtils.removeEnd(clazz.getSimpleName(), "Entity");
		String table = PropertyNamingStrategy.SnakeCase.translate(entityName);

		String sql = "insert into " + table + " (" + Joiner.on(",").join(fieldList) + ") values (" + Joiner.on(",").join(valueList) + ");";
		return sql;
	}
}
